import { View } from './View';
import { Action } from './Action';

/**
 * ViewController class - Contains business logic and handles events.
 */
export abstract class ViewController {
  private _id: string;
  private _view: View | null = null;
  private _actions: Action[] = [];
  private _active: boolean = true;

  /**
   * Create a new ViewController
   * @param id Controller identifier
   */
  constructor(id: string) {
    this._id = id;
  }

  /**
   * Get the controller ID
   */
  public get id(): string {
    return this._id;
  }

  /**
   * Get the view this controller is attached to
   */
  public get view(): View | null {
    return this._view;
  }

  /**
   * Set the view for this controller
   * @param view The view to attach to
   */
  public setView(view: View): void {
    this._view = view;
    this.onViewSet();
  }

  /**
   * Get whether this controller is active
   */
  public get active(): boolean {
    return this._active;
  }

  /**
   * Set whether this controller is active
   */
  public set active(value: boolean) {
    if (this._active !== value) {
      this._active = value;
      
      // Update active state of all actions
      for (const action of this._actions) {
        action.updateState();
      }
      
      if (value) {
        this.onActivated();
      } else {
        this.onDeactivated();
      }
    }
  }
  /**
   * Register an action with this controller
   * @param action The action to register
   */
  public registerAction(action: Action): void {
    if (!this._actions.includes(action)) {
      console.log(`ViewController ${this._id}: Registering action ${action.id}`);
      this._actions.push(action);
      action.setController(this);
    }
  }

  /**
   * Get all actions registered with this controller
   */
  public get actions(): Action[] {
    return [...this._actions];
  }

  /**
   * Called when the view is set
   */
  protected onViewSet(): void {
    console.log(`ViewController ${this._id}: View set to ${this._view?.id}`);
    // To be overridden by subclasses
  }

  /**
   * Called when the controller is activated
   */
  protected onActivated(): void {
    console.log(`ViewController ${this._id}: Activated`);
    // To be overridden by subclasses
  }

  /**
   * Called when the controller is deactivated
   */
  protected onDeactivated(): void {
    // To be overridden by subclasses
  }
}
